//
//  YJSystemCodeViewController.m
//  AndCampus
//
//  Created by 史宵宵 on 2017/11/16.
//  Copyright © 2017年 史宵宵. All rights reserved.
//

#import "YJSystemCodeViewController.h"
#import "loginTextField.h"
#import "YJStudentTelCerViewController.h"
#import "YJUserEditViewController.h"
#import "GLPickerView.h"

@interface YJSystemCodeViewController ()<UITextFieldDelegate>

@property (nonatomic,weak) UITextField *firstField;
@property (nonatomic,assign) int systemCodeNumber;//系统码的个数
@property (nonatomic,strong) NSMutableArray *textValeArray; //数组的值 数组

@property (nonatomic,weak) UILabel *teacherLabel;//显示父亲母亲的label
@end

@implementation YJSystemCodeViewController
- (NSMutableArray *)textValeArray{
    if (!_textValeArray) {
        _textValeArray = [NSMutableArray array];
    }
    return _textValeArray;
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleDefault;
    
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    [Global setStatusBarBackgroundColor:[UIColor clearColor]];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    //    [self.navigationController setNavigationBarHidden:NO animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.systemCodeNumber = 1;
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.frame = CGRectMake(0, 0, kScreenW, kScreenH);
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self creatView];
    self.textValeArray = [NSMutableArray arrayWithObjects:@"", nil];
}

- (void)creatView{
    UIView *headView = [[UIView alloc]init];
    headView.backgroundColor = [UIColor whiteColor];
    headView.frame = CGRectMake(0, 0, kScreenW, kScreenH / 7 + kScreenW / 3 + 20);
    
    UIButton *backButton = [[UIButton alloc]init];
    backButton.frame = CGRectMake(0, 20, 50, 50);
    [backButton setImage:[UIImage imageNamed:@"black_back"] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [headView addSubview:backButton];
    
    UIImageView *logoImageView = [[UIImageView alloc]init];
    logoImageView.frame = CGRectMake(kScreenW / 3, kScreenH / 7, kScreenW / 3 , kScreenW / 3 );
    logoImageView.contentMode = UIViewContentModeScaleAspectFill;
    logoImageView.image = [UIImage imageNamed:@"Login_sign"];
    [headView addSubview:logoImageView];
    if (self.role == KSystemRolePerson){
        UIButton *skipButton = [[UIButton alloc]init];
        [skipButton setTitle:@"跳过" forState:UIControlStateNormal];
        [skipButton setTitleColor:KTEXTMAINCOLOR forState:UIControlStateNormal];
        skipButton.frame = CGRectMake(kScreenW - 70, 10, 60, 20);
        [skipButton addTarget:self action:@selector(skipEnterMain) forControlEvents:UIControlEventTouchUpInside];
        [headView addSubview:skipButton];
    }
    if (self.role == KSystemRoleTeacher) {
        headView.frame = CGRectMake(0, 0, kScreenW, kScreenH / 7 + kScreenW / 3 + 90);
        
        UILabel *textLabel = [[UILabel alloc]init];
        textLabel.frame = CGRectMake(20, CGRectGetMaxY(logoImageView.frame) + 50, kScreenW - 40 , 40);
        textLabel.text = @"  与时老师";
        textLabel.userInteractionEnabled = YES;
        textLabel.layer.borderColor = [UIColor lightGrayColor].CGColor;
        textLabel.layer.borderWidth = 1;
        textLabel.layer.cornerRadius = 2;
        [headView addSubview:textLabel];
        
        textLabel.userInteractionEnabled = YES;
        [textLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapLabel:)]];
        self.teacherLabel = textLabel;
        
        UIImageView *moreImage = [[UIImageView alloc]init];
        moreImage.frame = CGRectMake(CGRectGetWidth(textLabel.frame) - 20, 17, 10, 6);
        moreImage.image = [UIImage imageNamed:@"arrow_down"];
        [textLabel addSubview:moreImage];
    }
    self.tableView.tableHeaderView = headView;
        
    
    UIView *footView = [[UIView alloc]init];
    footView.backgroundColor = [UIColor whiteColor];
    footView.frame = CGRectMake(0, 0, kScreenW, 150);
    self.tableView.tableFooterView = footView;
    
    if (self.role != KSystemRoleStudent) {
        UIButton *moreButton = [[UIButton alloc]init];
        moreButton.frame = CGRectMake(20, 5, kScreenW - 40, 40);
        [moreButton setTitle:@"+添加" forState:UIControlStateNormal];
        [moreButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [moreButton addTarget:self action:@selector(addSystemCode) forControlEvents:UIControlEventTouchUpInside];
        moreButton.userInteractionEnabled = YES;
        moreButton.layer.cornerRadius = 5;
        moreButton.layer.borderWidth = 1;
        moreButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
        [footView addSubview:moreButton];
    }
    
    
    //用户协议 @"同意《与时校园用户注册协议》"
    CustomeButton *userAgreementButton = [[CustomeButton alloc]initWithRelativeAlignment:KRelativeAlignmentRight titleNormal:@"同意《与时校园用户注册协议》" imageNormal:@"checkbox_checked" frame:CGRectMake(20, self.role == KSystemRoleStudent ? 5:40 + 10, kScreenW - 40, 20) titleRect:CGRectMake(20, 0, kScreenW - 120, 20) imageRect:CGRectMake(0, 2,15, 15) textAlignment:NSTextAlignmentLeft font:[UIFont systemFontOfSize:12] titleColor:KHEADERTITLECOLOR];
    [userAgreementButton addTarget:self action:@selector(userAgreement:) forControlEvents:UIControlEventTouchUpInside];
    [footView addSubview:userAgreementButton];
    
    //确定
    CompleteButton *loginButton = [[CompleteButton alloc]initWithFrame:CGRectMake(CGRectGetMinX(userAgreementButton.frame), CGRectGetMaxY(userAgreementButton.frame) + 10, CGRectGetWidth(userAgreementButton.frame),40) bgColor:KBACKNAVIGATIONCOLOR tColor:[UIColor whiteColor] text:@"确定"];
    if (self.role == KUserEditPerson) {
        [loginButton addTarget:self action:@selector(bindSystemCode) forControlEvents:UIControlEventTouchUpInside];
    }else{
        [loginButton addTarget:self action:@selector(verificationSystemCode) forControlEvents:UIControlEventTouchUpInside];
    }
    [footView addSubview:loginButton];
}

- (NSInteger )numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.systemCodeNumber;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:nil];
        cell.selectionStyle=UITableViewCellSelectionStyleNone;

    loginTextField *loginTF = [[loginTextField alloc]initWithFrame:CGRectMake(20, 5, kScreenW - 40 , 40) placeholder:@"输入系统注册码" imageStr:@""];
    loginTF.tag = 2000 + indexPath.row;
    loginTF.text=self.textValeArray[indexPath.row];
    loginTF.keyboardType = UIKeyboardTypeAlphabet;
    loginTF.delegate = self;
    [cell.contentView  addSubview:loginTF];
    if (indexPath.row != 0) {
        loginTF.frame = CGRectMake(20, 5, kScreenW - 74 , 40);
        
        UIButton *button = [[UIButton alloc]init];
        button.frame = CGRectMake(CGRectGetMaxX(loginTF.frame) + 10, CGRectGetMinY(loginTF.frame) + 8, 24, 24);
        button.backgroundColor = [UIColor redColor];
        button.clipsToBounds = YES;
        button.layer.cornerRadius = 12;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        [button setTitle:@"—" forState:UIControlStateNormal];
        [cell.contentView  addSubview:button];
        button.tag = 3000 + indexPath.row;
        [button addTarget:self action:@selector(deleteCode:) forControlEvents:UIControlEventTouchUpInside];
    }


    return cell;
}
- (void)deleteCode:(UIButton*)sender{
    [self.tableView endEditing:YES];
    self.systemCodeNumber --;
    [self.textValeArray removeObjectAtIndex:sender.tag - 3000];
    [self.tableView reloadData];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    [self.textValeArray replaceObjectAtIndex:textField.tag - 2000 withObject:textField.text];
    [textField resignFirstResponder];
    return YES;
}
-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self.textValeArray replaceObjectAtIndex:textField.tag - 2000 withObject:textField.text];
    [textField resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return [textField resignFirstResponder];
}

#pragma mark - 确定系统码
- (void)verificationSystemCode{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textValeArray[0])) {
        [Global showActivityWithView:self.view withText:@"请输入系统码"];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[self.textValeArray componentsJoinedByString:@","] forKey:@"sysCode"];   //学生验证码
    NSString *url;
    if (self.role == KSystemRoleStudent || self.role == KSystemRolePerson) {
        url = [JSPathUtil urlAppGetStudentInfo];
    }else{
        url = [JSPathUtil urlAppGetSchoolInfo];
    }
    [yjNetWorkManger requestType:GET andURL:url andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
            if (self.role == KSystemRoleStudent) {
                YJStudentTelCerViewController *studentTelCerVC = [[YJStudentTelCerViewController alloc]init];
                studentTelCerVC.telCerRole = KTelCerStudent;
                studentTelCerVC.studentInfo = dic;
                studentTelCerVC.sysCode = [self.textValeArray componentsJoinedByString:@","];
                [self.navigationController pushViewController:studentTelCerVC animated:YES];
            }else if (self.role == KSystemRolePerson){
                YJUserEditViewController *userEditVC = [[YJUserEditViewController alloc]init];
                userEditVC.userEditRole = KUserEditPerson;
                [self.navigationController pushViewController:userEditVC animated:YES];
            }else if (self.role == KSystemRoleTeacher){
               
                YJStudentTelCerViewController *studentTelCerVC = [[YJStudentTelCerViewController alloc]init];
                studentTelCerVC.telCerRole = KTelCerTeacher;
                studentTelCerVC.sysCode = [self.textValeArray componentsJoinedByString:@","];
                studentTelCerVC.studentInfo = dic;
                studentTelCerVC.identTeacher = self.teacherLabel.text;
                [self.navigationController pushViewController:studentTelCerVC animated:YES];
            }
            
        }
    }];
}
#pragma mark - 绑定系统码
- (void)bindSystemCode{
    [self.tableView endEditing:YES];
    if (strIsEmpty(self.textValeArray[0])) {
        [Global showActivityWithView:self.view withText:@"请输入系统码"];
        return;
    }
    YJNetWorkManger *yjNetWorkManger =  [YJNetWorkManger shareManager];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:[self.textValeArray componentsJoinedByString:@","] forKey:@"sysCode"];   //学生验证码
    [dic setValue:@"1" forKey:@"type"];   //学生验证码
    [dic setValue:[Global getUserTokenInfo] forKey:@"token"]; //用户的token
    [yjNetWorkManger requestType:POST andURL:[JSPathUtil urlAppBindInfo] andParmas:dic andComplition:^(id response, BOOL isuccess) {
        if (isuccess) {
//            NSMutableDictionary *dic = [[NSMutableDictionary alloc]initWithDictionary:response];
            if (self.role == KSystemRolePerson){
                YJUserEditViewController *userEditVC = [[YJUserEditViewController alloc]init];
                userEditVC.userEditRole = KUserEditPerson;
                [self.navigationController pushViewController:userEditVC animated:YES];
            }
        }
    }];
}
#pragma mark - 添加系统码
- (void)addSystemCode{
    
    [self.tableView endEditing:YES];
    self.systemCodeNumber ++;
    [self.textValeArray addObject:@""];
    [self.tableView reloadData];
}
#pragma mark - 选择与时老师，学校老师，志愿者
- (void)tapLabel:(UITapGestureRecognizer *)tap{
    GLPickerView *pickView= [[GLPickerView alloc]initDatePackerWithDataArray:@[@"与时老师",@"学校老师",@"志愿者"] Response:^(NSString *title) {
        self.teacherLabel.text = [NSString stringWithFormat:@"  %@",title];
    }];
    [pickView show];
}
#pragma mark - 同意用户协议
- (void)userAgreement:(UIButton *)sender{
    sender.selected = !sender.selected;
    
    [sender setImage:sender.selected ? [UIImage imageNamed:@"checkbox_unchecked"]:[UIImage imageNamed:@"checkbox_checked"] forState:UIControlStateNormal];
}
#pragma mark - 跳过
- (void)skipEnterMain{
    YJUserEditViewController *userEditVC = [[YJUserEditViewController alloc]init];
    userEditVC.userEditRole = KUserEditPerson;
    [self.navigationController pushViewController:userEditVC animated:YES];
}
#define mark - 返回
- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
